package com.mf.morefun.ui.userinfo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.LoginBean;
import com.mf.morefun.requestbean.RequestLoginBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.ui.HomePagerActivity;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.widget.LoginErrorDialog;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.FileUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseBusActivity {
    @BindView(R.id.edit_user)
    EditText editUser;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.v_username)
    View vUsername;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.iv_show)
    ImageView ivShow;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.v_password)
    View vPassword;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    private SPUtils mSPutils;
    private RoundProcessDialog roundProcessDialog;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPutils = new SPUtils(getApplicationContext());
        roundProcessDialog = new RoundProcessDialog(LoginActivity.this, "登录中...");
    }

    @Override
    protected void initData() {
        editUser.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vUsername.setBackgroundResource(R.color.main_default_color);
                    vPassword.setBackgroundColor(0xffC5C5C5);
                }
            }
        });
        editPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    vUsername.setBackgroundColor(0xffC5C5C5);
                    vPassword.setBackgroundResource(R.color.main_default_color);
                }
            }
        });
        if (!StringUtils.isEmpty(mSPutils.getString(Configuration.USERPHONE))){
            editUser.setText(mSPutils.getString(Configuration.USERPHONE));
        }
//        editUser.setText("18664990220");
//        editPassword.setText("123456");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //只要存用户名
    }
    int count = 0;
    @OnClick({R.id.iv_clear, R.id.tv_forget, R.id.iv_show, R.id.tv_login, R.id.tv_register})
    public void onViewClicked(View view) {
        Intent mIntent = null;
        switch (view.getId()) {
            case R.id.iv_clear:
                editUser.setText("");
                break;
            case R.id.tv_forget:
                mIntent = new Intent(LoginActivity.this, FirstPasswordActivity.class);
                startActivity(mIntent);
                break;
            case R.id.iv_show:
                if ((count % 2) == 0) {
                    ivShow.setImageResource(R.mipmap.eye_show);
                    editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    ivShow.setImageResource(R.mipmap.not_show_password);
                    editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                count++;
                break;
            case R.id.tv_login:
                if (StringUtils.isEmpty(editUser.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "手机不能为空", 100);
                    return;
                }
                if (StringUtils.isEmpty(editPassword.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "密码不能为空", 100);
                    return;
                }
                if (editUser.getText().toString().length() != 11 || !editUser.getText().toString().substring(0, 1).equals("1")) {
                    ToastUtils.show(getApplicationContext(), "请输入正确的手机号码", 100);
                    return;
                }
                initLogin(editUser.getText().toString(), editPassword.getText().toString());
                break;
            case R.id.tv_register:
                mIntent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(mIntent);
                finish();
                break;
        }
    }
    private  LoginErrorDialog dialog;
    private void initLogin(String user, String password) {
        if(null != roundProcessDialog){
            roundProcessDialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.LOGIN);
        RequestLoginBean bean = new RequestLoginBean();
        bean.setPhone(user);
        bean.setPassword(FileUtils.md5(password));
        params.setBodyContent(JSON.toJSONString(bean));
        params.setCharset("UTF-8");
        params.addHeader("Content-Type", "application/json");
        params.setConnectTimeout(10000);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog && dialog.isShowing()){
                    dialog.dismiss();
                }
                if(null != roundProcessDialog && roundProcessDialog.isShow()){
                    roundProcessDialog.cancel();
                }
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    MoreFunApplication.loginBean = JSON.parseObject(result, LoginBean.class);
                    if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getUserType())){
                        MoreFunApplication.loginBean.getResult().setUserType("1");
                    }
                    if (MoreFunApplication.loginBean.getErrorCode() == 0) {
                        mSPutils.putString(Configuration.USERID, MoreFunApplication.loginBean.getResult().getId());
                        mSPutils.putString(Configuration.USERPHONE, user);
                        mSPutils.putString(Configuration.USERPASSWORD, password);
                        if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getEnableEnd())){
                            dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, "账号异常");
                            dialog.show();
                        }else {
                            try {
                                if (MoreFunApplication.loginBean.getResult().getEnableEnd().length() == 10){
                                    long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(MoreFunApplication.loginBean.getResult().getEnableEnd() + " 23:59:59").getTime();
                                    long currentTime = System.currentTimeMillis();
                                    if (enableTime >= currentTime) {
                                        startActivity(new Intent(LoginActivity.this, HomePagerActivity.class));
                                        finish();
                                    } else {
                                        dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, "账号已过期");
                                        dialog.show();
                                    }
                                }else {
                                    long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(MoreFunApplication.loginBean.getResult().getEnableEnd()).getTime();
                                    long currentTime = System.currentTimeMillis();
                                    if (enableTime >= currentTime) {
                                        startActivity(new Intent(LoginActivity.this, HomePagerActivity.class));
                                        finish();
                                    } else {
                                        dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, "账号已过期");
                                        dialog.show();
                                    }
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, "账号异常");
                                dialog.show();
                            }
                        }
                    } else {
                        dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, MoreFunApplication.loginBean.getMessage());
                        dialog.show();
                    }
                } else {
                    dialog = new LoginErrorDialog(LoginActivity.this, R.style.loginerrordialog, "");
                    dialog.show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if(null != roundProcessDialog && roundProcessDialog.isShow()){
                    roundProcessDialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(LoginActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

}
